package com.quick.im.client.component;

import com.quick.im.client.handler.NettyClientHandler;
import com.quick.im.common.util.ProtobufDecoder;
import com.quick.im.common.util.ProtobufEncoder;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.net.InetAddress;
import java.net.UnknownHostException;

@Component
@Slf4j
public class NettyClientConfig {

    @Value("${netty.server.host}")
    private String serverHost;

    @Value("${netty.server.port}")
    private int serverPort;

    public void start() throws InterruptedException, UnknownHostException {
        NioEventLoopGroup group = new NioEventLoopGroup();

        try {
            Bootstrap bootstrap = new Bootstrap();
            bootstrap.group(group)
                    .channel(NioSocketChannel.class)
                    .handler(new ChannelInitializer<Channel>() {
                        @Override
                        protected void initChannel(Channel ch) throws Exception {
                            ch.pipeline()
                                    .addLast(new ProtobufDecoder())  // 解码器
                                    .addLast(new ProtobufEncoder())  // 编码器
                                    .addLast(new NettyClientHandler());  // 客户端处理器
                        }
                    });
            InetAddress localHost = InetAddress.getLocalHost();
            log.info("启动netty server success ip:{}----->port:{}",localHost.getHostAddress(),serverPort);
            bootstrap.connect(serverHost, serverPort).sync();  // 连接到服务器
        } finally {
//            group.shutdownGracefully();
        }
    }
}
